package com.reabam.tryshopping.h5.reabampos;

import androidx.annotation.NonNull;
import android.app.Activity;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import android.util.Log;

/*
 Flutter项目与android通讯插件
  需要在flutter的MainActivity.java中注册

  import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

@Override
    public void configureFlutterEngine(FlutterEngine flutterEngine){
        super.configureFlutterEngine(flutterEngine);

        //给当前页面注册自定义临时android插件
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        XFlutterProjectAndroidPlugin.registerWith(flutterEngine, this);

    }
 */
public class XFlutterProjectAndroidPlugin implements MethodCallHandler {

  public static final String CHANNEL = "x_project_channel";
  static MethodChannel channel;

  private Activity activity;
  private XFlutterProjectAndroidPlugin(Activity activity) {
    this.activity = activity;
  }

  public static void registerWith(FlutterEngine flutterEngine, FlutterActivity activity) {
    channel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
    XFlutterProjectAndroidPlugin projectAndroidPlugin = new XFlutterProjectAndroidPlugin(activity);
    //在此通道上接收方法调用的回调
    channel.setMethodCallHandler(projectAndroidPlugin);
  }

  @Override
  public void onMethodCall(MethodCall call, MethodChannel.Result result) {
    Log.i("XSDK", "flutter项目调用android原生方法：method=" + call.method+", arguments="+ call.arguments.toString());

    if (call.method.equals("demo_test")) {
      //返回通知flutter的参数
      nativeSendMessageToFlutter("type_demo_1","ok");
      result.success("success");
    }else if(call.method.equals("goBack")){
      activity.finish();
      result.success("success");
    }
    else {
      result.notImplemented();
    }
  }


  //原生发送消息通知flutter
  public static void nativeSendMessageToFlutter(String method,String json){
    channel.invokeMethod(method, json);
//      channel.invokeMethod("flutterMedia", "from android", new MethodChannel.Result() {
//        @Override
//        public void success(Object o) {
//          // 这里就会输出 "Hello from Flutter"
//          Log.i(">>>>>>>>>>debug", o.toString());
//        }
//        @Override
//        public void error(String s, String s1, Object o) {
//        }
//
//        @Override
//        public void notImplemented() {
//
//        }
//      });

  }


}
